# coding:utf-8
# @Time : 2021/4/30 13:57
# @File : user.py
from app import login_manager
from app import login_auth
from sqlalchemy import SmallInteger, Column, String, Enum, Integer
from werkzeug.security import generate_password_hash, check_password_hash
from app.models import BaseModel
from flask_login import UserMixin


class User(UserMixin, BaseModel):
    __tablename__ = 't_user'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

    is_active = Column(SmallInteger, nullable=False, default=1)  # 是否被冻结
    is_admin = Column(SmallInteger, nullable=False, default=0)  # 是否是管理员
    username = Column(String(64), unique=True, nullable=False)  # 账号
    _password = Column('password', String(128), nullable=False)  # 密码
    nickname = Column(String(24), nullable=False)  # 昵称
    sex = Column(Enum('未设置', '男', '女'), nullable=False, default='未设置')  # 性别
    coin = Column(Integer, nullable=False, default=0)  # 金币

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)


@login_manager.user_loader
def get_user(uid):
    return User.query.filter_by(id=uid).first()


@login_auth.verify_password
def verify_password(username, password):
    print('登录验证')
    user = User.query.filter_by(username=username).first()
    if user and user.password == password:
        print('密码正确')
        # 返回的数据是下面auth.current_user拿到的
        return user
